package gui;

import dal.object.MapObject;
import dal.object.grounds.Ice;
import dal.object.grounds.Sand;
import gui.event.SwitchObject;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;


@SuppressWarnings("serial")
public class GroundDrawer extends JPanel {
	private int halfImageWidth;
	private int imageWidth;
	private int imageHeight75;
	private int imageHeight25;
	private Image img;
	private Graphics gr;
	private Point location;
	private Vector<MapObject> vmo;
	private Dimension dimension;
	
	public GroundDrawer(Dimension dim/*MapStruct ms*/) {
		dimension = dim; // ms.getDimension();

		vmo = new Vector<MapObject>();
		
		for(int i = 0; i < dimension.width * dimension.height; ++i){
			if((int) (Math.random() * 2) == 0) {
				vmo.add(new Sand());
			} else {
				vmo.add(new Ice());
			}
		}

		this.addMouseListener(new SwitchObject(vmo));
		
		imageWidth = 38; //img.getWidth();
		halfImageWidth = 19; //imageWidth/2;
		imageHeight75 = 33; //(int) (img.getHeight() * 0.75);
		imageHeight25 = 11; //(int) (img.getHeight() * 0.25);
		
		// Setting panel size
		this.setSize(new Dimension(dimension.width * imageWidth + ((dimension.height > 1) ? halfImageWidth : 0), dimension.height * imageHeight75 + imageHeight25));
		// 
	}
	
	// Drawing grounds
	protected void paintComponent(Graphics g) {
		if (img == null) {
			img = createImage(getWidth(), getHeight());
			gr = img.getGraphics();
			gr.setColor(Color.BLACK);
			gr.fillRect(0, 0, getWidth(), getHeight());
			
			location = new Point(0,0);
			
			// Setting MapObjects' location and drawing them
			for (int i = 0; i < dimension.getHeight(); i++) {
				if (i%2 == 0)
					location.x = 0;
				else
					location.x = halfImageWidth;
				
				for (int j = 0; j < dimension.getWidth(); j++) {
					vmo.get((int) (i * dimension.getWidth() + j)).setLocation(location);
					vmo.get((int) (i * dimension.getWidth() + j)).drawObject(gr);
					location.x += imageWidth;
				}
				location.y += imageHeight75;
			}
		}
		
		g.drawImage(img, 0, 0, null);
	}
}